const pageHelper = require('../../../../../helper/page_helper.js');
const helper = require('../../../../../helper/helper.js');
const cloudHelper = require('../../../../../helper/cloud_helper.js');
const validate = require('../../../../../helper/validate.js');
const ProjectBiz = require('../../../biz/project_biz.js');
const projectSetting = require('../../../public/project_setting.js');
const setting = require('../../../../../setting/setting.js');
const PassportBiz = require('../../../../../comm/biz/passport_biz.js');

Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		isLoad: false,
		isEdit: false,
		showPrivacy: false,
		authorized: true,
		mobileCheck: setting.MOBILE_CHECK
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		wx.getPrivacySetting({
			success: res => {
			  // 返回结果为: res = { needAuthorization: true/false, privacyContractName: '《xxx隐私保护指引》' }
			  if (res.needAuthorization) {
				// 需要弹出隐私协议
				this.setData({
				  showPrivacy: true,
				  privacyContractName: res.privacyContractName,
				  authorized: false
				})
			  } else {
				// 用户已经同意过隐私协议，所以不需要再弹出隐私协议，也能调用已声明过的隐私接口
				// wx.getUserProfile()
				// wx.chooseMedia()
				// wx.getClipboardData()
				// wx.startRecord()
				this.setData({
					showPrivacy: false,
					privacyContractName: res.privacyContractName,
					authorized: true
				})
			  }
			},
			fail: () => {},
			complete: () => {}
		})
		ProjectBiz.initPage(this);

		if (options && options.retUrl)
			this.data.retUrl = decodeURIComponent(options.retUrl);

		await this._loadDetail();
	},

	_loadDetail: async function (e) {
		let opts = {
			title: 'bar'
		}
		let user = await cloudHelper.callCloudData('passport/my_detail', {}, opts);
		if (user) {
			return wx.redirectTo({ url: '../index/my_index' });
		}

		this.setData({
			isLoad: true,

			fields: projectSetting.USER_FIELDS,

			formName: '',
			formMobile: '',
			formPic: '',
			formForms: []
		});
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {
	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	bindGetPhoneNumber: async function (e) {
		console.log('bindGetPhoneNumber')
		console.log(e)
		PassportBiz.getPhone(e, this);
	},

	bindPicTap: function (e) {  
		this.setData({
			formPic: e.detail.avatarUrl
		})
	},

	bindSubmitTap: async function (e) {
		if (!this.data.authorized) {
			wx.showToast({
				title: '请仔细阅读' + this.data.privacyContractName +'并同意该指引',
				icon: 'none'
			});
			return
		}
		try {
			let data = this.data;

			// 数据校验 
			data = validate.check(data, projectSetting.USER_CHECK_FORM, this);
			if (!data) return;

			let forms = this.selectComponent("#cmpt-form").getForms(true);
			if (!forms) return;
			data.forms = forms;

			wx.showLoading({ title: '头像上传中' });
			let pic = await cloudHelper.transTempPicOne(this.data.formPic, 'user/', '', false);
			data.pic = pic;
			wx.hideLoading();

			data.status = projectSetting.USER_REG_CHECK ? 0 : 1;

			let opts = {
				title: '提交中'
			}
			await cloudHelper.callCloudSumbit('passport/register', data, opts).then(result => {
				if (result && helper.isDefined(result.data.token) && result.data.token) {

					// 用户需要审核，不能登录
					if (!projectSetting.USER_REG_CHECK) PassportBiz.setToken(result.data.token);

					let callback = () => {
						if (this.data.retUrl == 'back')
							wx.navigateBack();
						else if (this.data.retUrl)
							wx.redirectTo({
								url: this.data.retUrl,
							})
						else
							wx.reLaunch({ url: '../index/my_index' });
					}

					if (projectSetting.USER_REG_CHECK)
						pageHelper.showModal('注册完成，等待系统审核', '温馨提示', callback);
					else
						pageHelper.showSuccToast('注册成功', 1500, callback);
				}
			});
		} catch (err) {
			console.error(err);
		}
	},
	handleAgreePrivacyAuthorization() {
		console.log('handleAgreePrivacyAuthorization')
		this.setData({
			authorized: true
		})
		// 用户同意隐私协议事件回调
		// 用户点击了同意，之后所有已声明过的隐私接口和组件都可以调用了
		// wx.getUserProfile()
		// wx.chooseMedia()
		// wx.getClipboardData()
		// wx.startRecord()
	  },
	  handleOpenPrivacyContract() {
		// 打开隐私协议页面
		wx.openPrivacyContract({
		  success: () => {
			  console.log('openPrivacyContract success')
		  }, 
		  fail: () => {
			console.log('openPrivacyContract fail')
		  },
		  complete: () => {
			console.log('openPrivacyContract complete')
		  }
		})
	  }
})